package com.extrace.ui.misc;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.view.MenuItemCompat;
import android.support.v4.widget.SearchViewCompat;
import android.text.TextUtils;
import android.view.ContextMenu;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.SearchView;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.ListFragment;

import com.extrace.loader.TransNodeListLoader;
import com.extrace.misc.model.TransNode;
import com.extrace.ui.main.R;

import java.util.ArrayList;

public class TransNodeListActivity extends AppCompatActivity {

    PlaceholderFragment list_fg;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

        FragmentManager fm = getSupportFragmentManager();

        if(fm.findFragmentById(android.R.id.content) == null) {
            list_fg = new PlaceholderFragment();
            fm.beginTransaction().add(android.R.id.content, list_fg).commit();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        list_fg.onActivityResult(requestCode, resultCode, data);
    }

    public static class PlaceholderFragment extends ListFragment {
        private TransNodeListAdapter mAdapter;
        private TransNodeListLoader mLoader;

        private TransNode selectItem;
        private int selectPosition;

        Intent mIntent;

        public PlaceholderFragment() {
        }

        @Override
        public void onActivityCreated(Bundle savedInstanceState) {
            super.onActivityCreated(savedInstanceState);

            // Give some text to display if there is no data.  In a real
            // application this would come from a resource.
            setEmptyText("查找网点!");

            // We have a menu item to show in action bar.
            setHasOptionsMenu(true);

            // Create an empty adapter we will use to display the loaded data.
            mAdapter = new TransNodeListAdapter(new ArrayList<TransNode>(), this.getActivity());
            setListAdapter(mAdapter);

            getListView().setChoiceMode(ListView.CHOICE_MODE_SINGLE);

            registerForContextMenu(getListView());	//getListView().setLongClickable(true);

            // Start out with a progress indicator.
            //setListShown(false);
            RefreshList("all");
            if (mIntent.hasExtra("Action")) {
                if(mIntent.getStringExtra("Action").equals("New")){
                    //mItem = new CustomerInfo();
                }
                else if(mIntent.getStringExtra("Action").equals("None")){
                    //mItem = new CustomerInfo();
                }
                else if(mIntent.getStringExtra("Action").equals("Edit")){
                    if (mIntent.hasExtra("TransNode")) {
                        selectItem = (TransNode) mIntent.getSerializableExtra("TransNode");
                        RefreshList(selectItem.getNodeName());
                    } else {
                        this.getActivity().setResult(RESULT_CANCELED, mIntent);
                        this.getActivity().finish();
                    }
                }
                else{
                    this.getActivity().setResult(RESULT_CANCELED, mIntent);
                    this.getActivity().finish();
                }
            }
            else{
                this.getActivity().setResult(RESULT_CANCELED, mIntent);
                this.getActivity().finish();
            }
        }

        @Override
        public void onAttach(Activity activity) {
            super.onAttach(activity);
            mIntent = activity.getIntent();
        }

        @Override
        public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
            // Inflate the menu; this adds items to the action bar if it is present.
            inflater.inflate(R.menu.transnode_list, menu);

            MenuItem item = menu.findItem(R.id.action_search);
            final SearchView searchView = (SearchView) item.getActionView();
            if (searchView != null) {

                SearchViewCompat.setOnQueryTextListener(searchView,
                        new SearchViewCompat.OnQueryTextListenerCompat() {
                            @Override
                            public boolean onQueryTextChange(String newText) {
                                // Called when the action bar search text has
                                // changed. Since this
                                // is a simple array adapter, we can just have
                                // it do the filtering.
                                return true;
                            }

                            @Override
                            public boolean onQueryTextSubmit(String query) {
                                if (!TextUtils.isEmpty(query)) {
                                    RefreshList(query);
                                    SearchViewCompat.setQuery(searchView, null,true);
                                }
                                return true;
                            }
                        });
                SearchViewCompat.setOnCloseListener(searchView,
                        new SearchViewCompat.OnCloseListenerCompat() {
                            @Override
                            public boolean onClose() {
                                if (!TextUtils.isEmpty(SearchViewCompat.getQuery(searchView))) {
                                    SearchViewCompat.setQuery(searchView, null,true);
                                }
                                return true;
                            }

                        });
                MenuItemCompat.setActionView(item, searchView);
            }
        }

        @Override
        public boolean onOptionsItemSelected(MenuItem item) {
            int id = item.getItemId();
            switch(id){
                case android.R.id.home:
                case R.id.action_ok:
                    SelectOk();	//返回给上层
                    return true;
                case R.id.action_edit:
                    EditItem();
                    return true;
                case R.id.action_new:
                    NewItem();
                    return true;
                case R.id.action_search:
                    return true;
            }
            return super.onOptionsItemSelected(item);
        }

        @Override
        public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
            super.onCreateContextMenu(menu, v, menuInfo);
            AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) menuInfo;

            //onListItemClick(null,null,info.position,0);

            selectItem = mAdapter.getItem(info.position);
            selectPosition = info.position;
            this.getActivity().setTitle(selectItem.getNodeName());
            menu.setHeaderTitle("客户: "+selectItem.getNodeName());
            menu.add(info.position, 1, 0, "选择");
            menu.add(info.position, 2, 1, "修改");
            //menu.add(info.position, 3, 2, "删除");
        }

        @Override
        public boolean onContextItemSelected(MenuItem item) {
            //AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
            if (item.getTitle().equals("选择")) {
                SelectOk();	//返回给上层
            } else if (item.getTitle().equals("修改")) {
                EditItem();	//编辑客户
            }
//          else if (item.getTitle().equals("删除")) {
//              DeleteItem();	//删除客户
//          }
            return super.onContextItemSelected(item);
        }

        @Override public void onListItemClick(ListView l, View v, int position, long id) {
            selectItem = mAdapter.getItem(position);
            selectPosition = position;
            this.getActivity().setTitle(selectItem.getNodeName());
        }

        public void onActivityResult(int requestCode, int resultCode, Intent data) {	//编辑界面的回调
            switch (resultCode) {
                case RESULT_OK:
                    TransNode transNode;
                    if (data.hasExtra("TransNode")) {
                        transNode = (TransNode) data.getSerializableExtra("TransNode");
                        if(requestCode == TransNodeEditActivity.INTENT_NEW){
                            mAdapter.getData().add(transNode);
                        }
                        else if(requestCode == TransNodeEditActivity.INTENT_EDIT){
                            mAdapter.setItem(transNode, selectPosition);
                        }
                        mAdapter.notifyDataSetChanged();
                    }
                    break;
                default:
                    break;
            }
        }

        private void SelectOk()
        {
            mIntent.putExtra("TransNode",selectItem);
            this.getActivity().setResult(RESULT_OK, mIntent);
            this.getActivity().finish();
        }

        private void EditItem()
        {
            Intent intent = new Intent();
            intent.setClass(this.getActivity(),TransNodeEditActivity.class);
            intent.putExtra("Action","Edit");
            intent.putExtra("TransNode",selectItem);
            this.getActivity().startActivityForResult(intent, TransNodeEditActivity.INTENT_EDIT);	//激发下层编辑
        }

        private void NewItem()
        {
            Intent intent = new Intent();
            intent.setClass(this.getActivity(),TransNodeEditActivity.class);
            intent.putExtra("Action","New");
            this.getActivity().startActivityForResult(intent, TransNodeEditActivity.INTENT_NEW);	//激发下层编辑-建立新的
        }

        private void DeleteItem()
        {
            try {
                //mLoader = new CustomerListLoader(mAdapter, this.getActivity());
                //mLoader.DeleteCustomer(selectItem.getID());
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        private void RefreshList(String name)
        {
            this.getActivity().setTitle("");
            if(name.equals("all"))
            {
                try {
                    mLoader = new TransNodeListLoader(mAdapter, this.getActivity());
                    mLoader.LoadTransNodeAll();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            else
            {
                try {
                    //mLoader = new CustomerListLoader(mAdapter, this.getActivity());
                    //mLoader.LoadCustomerListByName(name);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
